import service from '@/utils/request'

/**
 * get请求封装
 * @param url
 * @param params
 * @param tipsConfig {showSuccessMsg,showFailMsg,showLoading}
 * @returns {Promise<unknown>}
 */
export const get = async(url, params = {}, tipsConfig = {
  showSuccessMsg: false,
  showFailMsg: true,
  showLoading: false
}) => {
  let res = null
  try {
    res = await service({ url, method: 'get', params, tipsConfig })
  } catch (e) {
    res = { code: 50000, data: { e }, message: e.message }
  }
  return new Promise((resolve) => {
    resolve(res)
  })
}
/**
 *post请求封装
 * @param url
 * @param data
 * @param tipsConfig {showSuccessMsg,showFailMsg,showLoading}
 * @returns {Promise<unknown>}
 */
export const post = async(url, data = {}, tipsConfig = {
  showSuccessMsg: true,
  showFailMsg: true,
  showLoading: true
}) => {
  let res = null
  try {
    res = await service({ url, method: 'post', data, tipsConfig })
  } catch (e) {
    res = { code: 50000, data: { e }, message: e.message }
  }
  return new Promise((resolve) => {
    resolve(res)
  })
}

/**
 * post 文件上传请求参数
 * @param {String} url 请求地址
 * @param {Object} data 请求参数
 * @param {Function} uploadProgress 进度条回调方法
 * @param {showSuccessMsg,showFailMsg,showLoading} myConfig 请求状态显示
 */
export const upload = async(url, data, uploadProgress = () => { }, myConfig = {
  showSuccessMsg: true,
  showFailMsg: false,
  showLoading: false
}) => {
  let res = null
  const headers = { 'Content-Type': 'multipart/form-data' }
  try {
    res = service({
      url: url,
      method: 'post',
      headers,
      data,
      onUploadProgress: uploadProgress,
      myConfig
    })
  } catch (e) {
    res = { code: 50000, data: { e }, message: e.message }
  }
  return new Promise((resolve) => {
    resolve(res)
  })
}

/**
 * get文件下载封装
 * @param url 请求地址
 * @param data 请求参数
 * @param tipsConfig 请求状态显示
 * @returns {Promise<unknown>}
 */
export const getFile = async(url, data, tipsConfig = {
  showSuccessMsg: true,
  showFailMsg: true,
  showLoading: true
}) => {
  let res = null
  const headers = { 'Content-Type': 'application/vnd.ms-excel; charset=utf8' }
  try {
    const resData = await service({ url: url, method: 'get', headers, params: data, responseType: 'blob', tipsConfig })
    res = { code: 20000, data: resData, message: '数据获取成功' }
  } catch (e) {
    res = { code: 50000, data: { e }, message: e.message }
  }
  return new Promise((resolve) => {
    resolve(res)
  })
}

